﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MusicDownload
{
    public partial class FormSearch : Form
    {
        DelayLogic delayLogic = new DelayLogic();
        UIChannel<List<MusicModel>> musicChannel;
        UIChannel<Exception> exceptionChannel;

        public FormSearch()
        {
            InitializeComponent();
        }

        private void MusicChannel_OnPopEvent(List<MusicModel> obj)
        {
            //Console.WriteLine("musics");
            //Console.WriteLine(JsonConvert.SerializeObject(obj));

            listView_musicList.Items.Clear();

            foreach (var item in obj)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = item.Title;
                //lvi.SubItems.Add(item.SongId.ToString());
                lvi.SubItems.Add(item.Author);
                lvi.SubItems.Add(item.Link);

                listView_musicList.Items.Add(lvi);
            }
        }

        private void textBox_userInput_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox_userInput_KeyDown(object sender, KeyEventArgs e)
        {
            delayLogic.Cancel();
        }

        private void textBox_userInput_KeyUp(object sender, KeyEventArgs e)
        {
            var text = textBox_userInput.Text;
            delayLogic.Register(1200, () =>
            {
                try
                {
                    musicChannel.Push(MusicSeacher.Search(text));
                }
                catch (Exception ex)
                {
                    exceptionChannel.Push(ex);
                }
            });
        }

        private void FormSearch_Load(object sender, EventArgs e)
        {
            musicChannel = new UIChannel<List<MusicModel>>();
            musicChannel.OnPopEvent += MusicChannel_OnPopEvent;

            exceptionChannel = new UIChannel<Exception>();
            exceptionChannel.OnPopEvent += ExceptionChannel_OnPopEvent;
        }

        private void ExceptionChannel_OnPopEvent(Exception obj)
        {
            MessageBox.Show(obj.Message);
        }
    }
}
